package concurrents;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestSocketThreadPool {

	static class ServiceThread implements Runnable{
		
		private Socket socket;
		
		public ServiceThread(Socket socket) {
			this.socket = socket;
		}
		@Override
		public void run() {
			System.out.println(socket.getInetAddress() + ":" + socket.getPort());
			try {
				DataInputStream dis = new DataInputStream(new BufferedInputStream( socket.getInputStream()) );
				OutputStream os = socket.getOutputStream();
				String in;
				while((in = dis.readLine()) != null){
					if(in.equals("bye"))	break;
					else{
						System.out.println("client:" + socket.getInetAddress() + ":" + socket.getPort()
								+ " say:" + in);
						os.write(in.getBytes("UTF-8"));
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	public static void main(String[] args) {
		
		boolean flag = true;
		
		ExecutorService pool = Executors.newFixedThreadPool(2);
		try{
			ServerSocket server = new ServerSocket(12345);
			System.out.println("开始监听");
			while(flag){
				Socket client = server.accept();
				pool.execute(new ServiceThread(client));
			}
			server.close();
		}catch(IOException ie){
			ie.printStackTrace();
		}
		
		
	}
}
